<?php

namespace app\admin\controller;

use think\Request;
class System extends Admin
{
    /**
     * 轮播图列表
     * @return \think\response\View
     * @throws \think\exception\DbException
     */
    public function banner()
    {
        $lists = \think\Db::table('banners')
            ->order('order desc')
            ->field('id,order,status,position,url,image')
            ->paginate(20);

        $banners = $lists->toArray();
        foreach ($banners['data'] as &$banner) {
            $video_info = \think\Db::table('videos')
                ->where('id',$banner['url'])
                ->field('name')
                ->find();
            $banner['video_name'] = $video_info['name'];
        }
        unset($banner);
        unset($video_info);

        $total = $lists->total();
        $page = $lists->render();

        $videos = \think\Db::table('videos')
            ->where('status',1)
            ->field('id,name')
            ->order('is_top desc,id desc')
            ->select();

        return view('banner',[
            'lists' => $banners['data'],
            'page' => $page,
            'total' => $total,
            'videos' => $videos
        ]);
    }

    /**
     * 添加轮播图
     * @return \think\response\Json
     */
    public function addBannerPost()
    {
        $validate = new \think\Validate([
            'url| 链接' => 'require',
            'file_url| 图片' => 'require',
            'position| 位置' => 'require',
        ]);
        $request_data = input();

        if (!$validate->check($request_data)) {
            return error($validate->getError());
        }

        $data = [
            'position' => $request_data['position'],
            'status' => $request_data['status'],
            'order' => $request_data['order'],
            'url' => $request_data['url'],
            'image' => $request_data['file_url'],
        ];
        \think\Db::table('banners')->insert($data);
        writeAdminLog(session('VideoAdmin.name'),' 添加轮播图 ' . $request_data['file_url']); //后台管理日志
        return success('添加成功！');
    }

    /**
     * 获取编辑信息
     * @return \think\response\Json
     */
    public function edit()
    {
        $validate = new \think\Validate([
            'id| ID' => 'require',
        ]);
        $request_data = input();

        if (!$validate->check($request_data)) {
            return error($validate->getError());
        }

        $info = \think\Db::table('banners')
            ->where('id',$request_data['id'])
            ->find();

        return success('轮播图信息！',$info);
    }

    /**
     * 提交编辑数据
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function editBannerPost()
    {
        $validate = new \think\Validate([
            'url| 链接' => 'require',
            'file_url| 图片' => 'require',
            'position| 位置' => 'require',
        ]);
        $request_data = input();

        if (!$validate->check($request_data)) {
            return error($validate->getError());
        }

        $data = [
            'position' => $request_data['position'],
            'status' => $request_data['status'],
            'order' => $request_data['order'],
            'url' => $request_data['url'],
            'image' => $request_data['file_url'],
        ];

        \think\Db::table('banners')->where('id',$request_data['id'])->update($data);
        writeAdminLog(session('VideoAdmin.name'),' 编辑轮播图:ID ' . $request_data['id']); //后台管理日志
        return success("编辑成功！");
    }

    /**
     * 更改状态
     */
    public function changeStatus()
    {
        $field = input('field');
        $id = input('id');
        $type = input('type');

        switch ($type){
            case 'banner': //轮播图
                $info = \think\Db::table('banners')
                    ->where('id',$id)
                    ->field("$field")
                    ->find();

                $status = $info[$field] == 1? 2 : 1;
                \think\Db::table('banners')
                    ->where('id',$id)
                    ->update(["$field" => "$status"]);

                writeAdminLog(session('VideoAdmin.name'),' 更改轮播状态：ID：' . $id); //后台管理日志
                break;
        }
    }


    /**
     * 删除
     */
    public function deleted()
    {
        $type = input('type');
        $id = input('id');

        switch ($type) {
            case 'banner': // 轮播图
                \think\Db::table('banners')
                    ->where('id',$id)
                    ->delete();

                writeAdminLog(session('VideoAdmin.name'),' 删除轮播ID：' . $id); //后台管理日志
                break;
        }
        return success('成功删除');
    }

    /**
     * 分享设置
     * @param Request $request
     * @return \think\response\View
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function share(Request $request)
    {
        if ($request->isPost()) {
            $validate = new \think\Validate([
                'share_app_url|app下载链接' => 'require',
            ]);
            if (!$validate->check($request->param())) {
                $this->error($validate->getError());
            }

            if(strpos($request->param('share_app_url'), 'http') === false) {
                $this->error('下载地址应包含http:// 或 https://');
            }

            foreach ($request->param() as $key => $value) {
                $item = \think\Db::table('system')->where('key',$key)->find();
                if($item) {
                    \think\Db::table('system')->where('key',$key)->update(['value' => $value]);
                }else{
                    \think\Db::table('system')->insert([
                        'key' => $key,
                        'value' => $value
                    ]);
                }
            }

            $this->success('设置成功');
        }

        $share_config = ['share_app_url'];
        foreach ($share_config as $config) {
            $item = \think\Db::table('system')->where(['key' => $config])->field('value')->find();
            $configs[$config] = $item['value'];
        }

        return view('share', compact('configs'));
    }

    /***
     * 声明设置
     * @param Request $request
     * @return \think\response\View
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function state(Request $request)
    {
        $type = $request->param('type');
        $type = empty($type) ? 'video' : $type;
        switch ($type){
            case 'video':
                $key = 'state_video';
                $title = '视频功能声明';
                break;
            case 'member':
                $key = 'state_member';
                $title = '用户协议';
                break;
            case 'copyright':
                $key = 'state_copyright';
                $title = '版权声明';
                break;
            case 'privacy':
                $key = 'state_privacy';
                $title = '隐私政策';
                break;
        }

        if ($request->isPost()) {
            $item = \think\Db::table('system')->where('key',$key)->find();
            if($item) {
                \think\Db::table('system')->where('key',$key)->update(['value' => $request->param($key)]);
            }else{
                \think\Db::table('system')->insert([
                    'key' => $key,
                    'value' => $request->param($key)
                ]);
            }
            $this->success('设置成功');
        }

        $item = \think\Db::table('system')->where(['key' => $key])->field('value')->find();
        $configs = $item['value'];

        return view('state', compact('configs','title'));
    }


    /**
     * 极光推送设置
     * @param Request $request
     * @return \think\response\View
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function push(Request $request)
    {
        if ($request->isPost()) {
            $validate = new \think\Validate([
                'push_app_key|推送key' => 'require',
                'push_master_secret|推送密钥' => 'require',
            ]);
            if (!$validate->check($request->param())) {
                $this->error($validate->getError());
            }

            foreach ($request->param() as $key => $value) {
                $item = \think\Db::table('system')->where('key',$key)->find();
                if($item) {
                    \think\Db::table('system')->where('key',$key)->update(['value' => $value]);
                }else{
                    \think\Db::table('system')->insert([
                        'key' => $key,
                        'value' => $value
                    ]);
                }
            }

            $this->success('设置成功');
        }

        $push_config = ['push_app_key','push_master_secret'];
        foreach ($push_config as $config) {
            $item = \think\Db::table('system')->where(['key' => $config])->field('value')->find();
            $configs[$config] = $item['value'];
        }

        return view('push', compact('configs'));
    }
}
